package com.atguigu.sh.juc;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 线程池
 *
 * @author daixl
 * @date 2021/6/20
 */
public class MyThreadPoolDemo {

    public static void main(String[] args) {
//        ExecutorService threadPool = Executors.newFixedThreadPool(5);//一池5个工作线程，类似银行有5个受理窗口
//        ExecutorService threadPool = Executors.newSingleThreadExecutor();//一池1个工作线程，类似银行有1个受理窗口
        ExecutorService threadPool = Executors.newCachedThreadPool();//一池n个工作线程，类似银行有n个受理窗口

        try {
            //模拟有10个客户过来银行办理业务，目前池子里只有5个受理窗口
            for (int i = 0; i < 10; i++) {
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "\t办理业务");
                    //暂停一会儿线程
                    try { TimeUnit.SECONDS.sleep( 1 ); } catch (InterruptedException e) { e.printStackTrace(); }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }
    }
}
